package log;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.dom4j.DocumentException;

import indi.zjh.dp.db.Session;
import indi.zjh.dp.error.UnsuportedFieldException;
import indi.zjh.dp.orm.Business;
import indi.zjh.dp.orm.Query;
import indi.zjh.dp.orm.Relation;
import indi.zjh.dp.orm.Result;
import indi.zjh.dp.type.String128;

public class Label extends Business {
	protected String128 name = new String128("undefined");
	protected Relation logs = new Relation(Log.class);
	
	/**
	 * 贴上日期标签
	 * @param session
	 * @throws Exception 
	 * @throws DocumentException 
	 * @throws UnsuportedFieldException 
	 * @throws ClassNotFoundException 
	 */
	public static void addDateLabel(Session session, Log log) throws ClassNotFoundException, UnsuportedFieldException, DocumentException, Exception
	{
		Date cur = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");
		
		Label label = null;
		String datalabel = sdf.format(cur);
		
		Query<Label> query = new Query<Label>(session);
		Result<Long> ids = query.find(Label.class, "`name` = '"+datalabel+"'").idResult();
		if(ids.count() > 0)
		{
			label = (Label)session.getById(Label.class, ids.iterator().next().longValue());
		}
		else
		{
			label = new Label();
			label.setName(sdf.format(cur));
		}
		
		label.getLogs().add(log);
		session.save(label);
	}
	
	@Override
	public String toDictString(Field f)
	{
		if(f.getName().equals("name"))
		{
			return "标签名称, 用来过滤日志, 可以使用多个标签同时过滤日志";
		}
		else if(f.getName().equals("logs"))
		{
			return "标签关联的日志记录";
		}
		
		return super.toDictString(f);
	}

	public String getName() {
		return name.string;
	}

	public void setName(String name) {
		this.name.string = name;
	}

	public Relation getLogs() {
		return logs;
	}

	@Override
	public String toString() {
		return "Label [name=" + name + ", logs=" + logs + ", _id=" + _id + ", _v=" + _v + "]";
	}
	
	
}
